package com.example.cet4try.activity;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.cet4try.R;
import com.example.cet4try.Utils.MyAsyncTask;
import com.example.cet4try.Utils.MySQLUtils;
import com.example.cet4try.Utils.Tools;
import com.example.cet4try.adapter.TableAdapter;
import com.example.cet4try.diyView.TopView;
import com.example.cet4try.myDialog.EditTextDialog;
import com.example.cet4try.myDialog.LoadDialog;

import java.util.ArrayList;

public class ActivityDatabaseManager extends AppCompatActivity {

    private RecyclerView db_show;
    private TextView load_m;
    private TextView selectItem = null;
    private int columns,pm_lineCount = -1,selectItemIndex = -1;
    private String tableName;
    private LoadDialog loadDialog;
    private ArrayList<String> data = new ArrayList<String>();
    private boolean isMySQL = true;
    private TableAdapter adapter;
    private Drawable k_grey,ks_blue;
    private EditTextDialog editTextDialog;
    private ArrayList<Integer> modifyResults = new ArrayList<Integer>();

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            boolean b = (boolean) msg.obj;
            if (b){
                db_show.setAdapter(adapter);
                loadDialog.dismiss();
            }
        }
    };

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_database_manager);

        Intent intent = getIntent();
        //columns = intent.getIntExtra("columns",4);
        String type = intent.getStringExtra("type");

        TopView db_name = findViewById(R.id.db_name);
        db_name.setmTitle(intent.getStringExtra("dbname"));

        loadDialog = new LoadDialog(this);
        loadDialog.setTitle("正在加载数据");
        loadDialog.show();

        ScrollView tb_scroll = findViewById(R.id.tb_scroll);
        db_show = findViewById(R.id.db_show);
        load_m = findViewById(R.id.load_m);
        k_grey = getResources().getDrawable(R.drawable.k_grey);
        ks_blue = getResources().getDrawable(R.drawable.ks_blue);
        editTextDialog = new EditTextDialog(this);

        editTextDialog.setOnSelectListener(new EditTextDialog.OnSelectListener() {
            @Override
            public void OnConfirm() {
                String text = editTextDialog.getText();
                selectItem.setText(text);

                if (text.equals(data.get(selectItemIndex))){
                    modifyResults.remove((Integer) selectItemIndex);
                }
                else {
                    modifyResults.add(selectItemIndex);
                }

                adapter.setItemData((int) selectItem.getTag(),text);

            }

            @Override
            public void onCancel() {

            }
        });

        switch (type){
            case "user":
                data.add("id");data.add("username");data.add("nickname");data.add("password");
                tableName = "users";
                break;
            case "feedback":
                data.add("id");data.add("time");data.add("content");data.add("user");data.add("nick");
                tableName = "feedback";
                break;
            case "cet4":
            case "cet6":
            case "unge":
                data.add("id");data.add("english");data.add("chinese");data.add("phonetic");data.add("example");
                tableName = "cet4word";
                isMySQL = false;
                break;
        }
        columns = data.size();

        new Thread(new Runnable() {
            @Override
            public void run() {
                //Log.e("mDatabaseManager", "getAllData");
                if (isMySQL)
                    MySQLUtils.getAllData(tableName,data);
                else
                    Tools.getAllWordData(tableName,data);
                adapter = new TableAdapter(ActivityDatabaseManager.this,data,columns);
                adapter.setOnItemClickListener(new TableAdapter.OnItemClickListener() {
                    @Override
                    public void OnItemClick(View view, int position) {
                        selectItemIndex = position;
                        if (selectItem != null){
                            selectItem.setBackground(k_grey);
                        }
                        selectItem = (TextView) view;
                        view.setBackground(ks_blue);
                        String[] itemData = adapter.getItemData(position);
                        editTextDialog.show_t(itemData[0],itemData[1]);
                        //editTextDialog.show();
                    }
                });
                Message message = handler.obtainMessage();
                message.obj = true;
                handler.sendMessage(message);
            }
        }).start();

        db_show.setLayoutManager(getLayoutManager());

        tb_scroll.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View view, int newLeft, int newTop, int oldLeft, int oldTop) {
                if (pm_lineCount == -1)
                    pm_lineCount = view.getHeight()/adapter.getItemHeight() + 1;
                if (selectItem != null){
                    selectItem.setBackground(k_grey);
                    selectItem = null;
                }
                int line = newTop/adapter.getItemHeight();
                int sy_lineCount = adapter.getLineCount() - line - pm_lineCount;
                if (sy_lineCount == 0){
                    adapter.loadMore();
                    show_loadmore();
                }

                //Log.e("DB------>", "当前行="+line+",剩余行="+sy_lineCount+",屏幕容纳"+pm_lineCount+"行");
            }
        });

        Button btn_save = findViewById(R.id.btn_save);
        btn_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                saving();
            }
        });


    }

    private GridLayoutManager getLayoutManager(){
        return new GridLayoutManager(ActivityDatabaseManager.this,columns){
            @Override
            public boolean canScrollVertically() {
                return false;
            }
            @Override
            public boolean canScrollHorizontally() {
                return super.canScrollHorizontally();
            }
        };
    }

    private void show_loadmore(){
        load_m.setVisibility(View.VISIBLE);

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                adapter.notifyDataSetChanged();
                load_m.setVisibility(View.GONE);
            }
        }, 200);
    }

    private void saving(){
        MyAsyncTask task = new MyAsyncTask(ActivityDatabaseManager.this,"正在提交");
        task.setOnExecute(new MyAsyncTask.OnExecute() {
            @Override
            public void before() {

            }

            @Override
            public void main() {
                for (int i = 0;i < modifyResults.size();i++){
                    int position = modifyResults.get(i);
                    String mkey = isMySQL?"id":"_id";
                    String mvalue = data.get(position-(position%columns));

                    String[] i_data = adapter.getItemData(position);

                    String where = "WHERE "+mkey+"="+mvalue;
                    String set = i_data[0]+"='"+i_data[1]+"'";
                    if (isMySQL)
                        MySQLUtils.updateData(tableName,set,where);
                    else
                        Tools.SQLiteupdateData(tableName,set,where);
                }
            }

            @Override
            public void after() {

                    Toast.makeText(ActivityDatabaseManager.this,"提交成功",Toast.LENGTH_SHORT).show();

            }
        });
        task.execute();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }


}
